package doc2db.interfaces.action;

import doc2db.DbManager.DbSelects;
import doc2db.UserProp;
import doc2db.table.DocTableCell;
import doc2db.table.DocTableHead;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *  When processing a batch of documents, and create a table with the
 * same name, the table structure is formed on the first document. If
 * the table does not contain all the columns that are in other files,
 * this leads to conflict negotiation. Its easily solved by adding the
 * necessary columns to an existing table in the database.
 * 
 * @author yura
 */
public class ConflictOutbreak {

    protected String tableName;
    
    /** last message */
    protected String msg;

    /**
     * Return  last message
     * @return last message 
     */
    public String getMsg() {
        return msg;
    }


    /**
     * Get the value of table name
     *
     * @return the value of table name
     */
    public String getTableName() {
        return tableName;
    }

    /**
     * Set the value of table name
     *
     * @param tableName new value of table name
     */
    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    /**
     * Create new instance with seted table name
     * @param tableName value of table name
     */
    public ConflictOutbreak(String tableName) {
        this.tableName = tableName;
    }

    /**
     *  Coordination table structures
     * @param docHead Table head of processing document
     * @param heads heads of table? thet allready exists
     * @return true if table structure changed
     */
    public boolean coordinatTableStruct(DocTableHead docHead, String[] heads){
        //if (compatibilityCheck(heads, docHead)) {
        //    return false;
        //}

        List<DocTableCell> set = new ArrayList<DocTableCell>();
        selectDifferentTitl(docHead, heads, set);

        for (DocTableCell cel : set) {
            String sql = getSql(tableName, cel.getName(), cel.getHead());
            System.out.println(sql);
            UserProp up = new UserProp();
            try {
                DbSelects query = new DbSelects(up.getURL(), up.getUserProp());
                boolean b = query.sendQueryUpdate(sql);
                if (!b){
                    throw new SQLException("can send query");
                }
            } catch (Exception ex) {
                msg = "невозможно добавить колонку:\n" + cel + "\n" + ex;
                return false;
            }
        }

        return true;
    }

    /**
     * selection of different titles, and store thay name in set
     * @param docHead Table head of processing document
     * @param heads heads of table? thet allready exists
     * @param set list with differents 
     */
    private void selectDifferentTitl(DocTableHead docHead, String[] heads, 
            List<DocTableCell> set) {

        for(int i = 0; i < docHead.getSize(); i++){
            DocTableCell get = docHead.get(i);
            String th = get.getName();
            boolean b = true;

            for (String h : heads) {
                if (h.equals(th)) {
                    b = false;
                    break;
                }
            }

            if (b) {
                set.add(get);
            }
        }
    }

    /**
     *  Compatibility Check
     * @param docHead Table head of processing document
     * @param heads heads of table? thet allready exists
     * @return true if tables structure compatibilitid
     */
    private boolean compatibilityCheck(String[] heads, DocTableHead docHead) {
        for (String h : heads) {
            boolean b = false;
            for (String th : docHead.get()) {
                if (h.equals(th)) {
                    b = true;
                    break;
                }
            }
            if (!b) {
                msg = "Таблицы в БД и в документе имеют расхождения";
                return true;
            }
        }
        return false;
    }

    /**
     * Generates a sql query to add a column, to a table in the database
     * @param table table name in database
     * @param column name of new column
     * @param type datatype of curent column
     * @return sql query
     */
    private String getSql(String table, String column, String type){
        return "ALTER TABLE \"" + table +
                "\" ADD COLUMN \"" + column + "\" \"" + type + "\"; ";
    }

}
